/**
 *
 */
;(function($){

    $.fn.offset = function(coordinates){

        if (coordinates) return this.each(function(index){
            var $this = $(this),
                coords = funcArg(this, coordinates, index, $this.offset()),
                parentOffset = $this.offsetParent().offset(),
                props = {
                    top:  coords.top  - parentOffset.top,
                    left: coords.left - parentOffset.left
                }

            if ($this.css('position') == 'static') props['position'] = 'relative'
            $this.css(props)
        })

        if (this.length==0) return null
        var obj = this[0].getBoundingClientRect();

        //如果元素或父元素display:none则获取到的宽高为0，此方法可获取计算后的宽高
        var style = window.getComputedStyle(this[0], null);

        return {
            top: obj.top + window.pageYOffset,
            left: obj.left + window.pageXOffset,
            width: getWidth(style),
            height: getHeight(style)
        }

    }

    // Override the `width` and `height` functions
    ;['width', 'height'].forEach(function (dimension) {
        $.fn[dimension] = function (value) {

            //如果宽高没有单位会赋值失败
            if (value && !/px|em|rem/i.test(value.toString())) value += "px";

            var offset, el = this[0],
                Dimension = dimension.replace(/./, function (m) { return m[0].toUpperCase() })
            if (value === undefined) return isWindow(el) ? el['inner' + Dimension] :
                isDocument(el) ? el.documentElement['offset' + Dimension] :
                    (offset = this.offset()) && offset[dimension]
            else return this.each(function (idx) {
                el = $(this)
                el.css(dimension, funcArg(this, value, idx, el[dimension]()))
            })
        }
    })

    var isFunction = $.isFunction;
    function isWindow(obj) { return obj != null && obj == obj.window }
    function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
    function funcArg(context, arg, idx, payload) {
        return isFunction(arg) ? arg.call(context, idx, payload) : arg
    }
    function getPixelNumber(str){
        return parseInt(str.replace("px", ""));
    }
    function getWidth(style){
        var width = 0;
        if (style.width.indexOf("px") > -1){
            width = getPixelNumber(style.width) + getPixelNumber(style.paddingLeft) + getPixelNumber(style.paddingRight);
        }
        return width;
    }
    function getHeight(style){
        var height = 0;
        if (style.height.indexOf("px") > -1){
            height = getPixelNumber(style.height) + getPixelNumber(style.paddingTop) + getPixelNumber(style.paddingBottom);
        }
        return height;
    }

})(Zepto);